﻿package com.urbansquall.utils
{
	import flash.events.*;
	import flash.text.*;
	import flash.utils.*;
	
	public class FPS extends TextField
	{
		protected var timer:Timer;
		protected var frames:int;
		protected var timeOfLastUpdate : Number;
		
		public function FPS()
		{
			defaultTextFormat = new TextFormat( "Verdana", 9, 0x000000 );
			timer = new Timer(1000);
			this.autoSize = TextFieldAutoSize.CENTER;
			this.text = "FPS";
			this.backgroundColor = 0xFFFFFF;
			this.background = true;
			this.selectable = false;
			timer.addEventListener( TimerEvent.TIMER, timerHandler );
			addEventListener( Event.ENTER_FRAME, enterFrameHandler );
			
			timer.start();
			
			timeOfLastUpdate = getTimer();
		}
		
		public function reset() : void
		{
			frames = 0;
			text = "FPS";
			timeOfLastUpdate = getTimer();
		}
		
		private function timerHandler(e:TimerEvent):void
		{
			var deltaTime : Number = calculateDeltaTime();
			text = String( Math.round( frames / (deltaTime / 1000 ) ) );
			frames = 0;
		}
		
		private function enterFrameHandler(e:Event):void
		{
			frames++;
		}
		
		private function calculateDeltaTime() : Number
		{
			var currentTime : Number = getTimer();
			var deltaTime : Number = currentTime - timeOfLastUpdate;
			timeOfLastUpdate = currentTime;
			return deltaTime;
		}
	}
	
}